﻿using EMoney.IStock.Client.Business.MC;
using EMoney.IStock.Client.DataAccess.Cpyx;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.Cpyx;
using EMoney.IStock.Client.Models.MC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EMoney.IStock.Client.Business.Cpyx
{
    /// <summary>
    /// 操盘英雄业务处理类
    /// </summary>
    public class CpyxBll
    {
        private object objCpyxArmory = new object();

        private const string CPYXARMORY_CACHED_KEY = "EMoney.IStock.Client.Business.Cpyx.CpyxBll.CpyxArmory";

        /// <summary>
        /// 获取排行榜数据
        /// </summary>
        /// <returns></returns>
        public string GetArmory(int userid,string flag)
        {
            string result = string.Empty;
            DateTime dtNow = DateTime.Now;
            string weekEndDate = string.Empty;

            switch (flag)
            {
                case "pw": //上周
                    weekEndDate = StringHelper.FormatDateTime(DateTimeHelper.GetSundayDate(dtNow.AddDays(-7)),"yyyyMMdd");
                    break;
                case "ppw": //上上周
                    weekEndDate = StringHelper.FormatDateTime(DateTimeHelper.GetSundayDate(dtNow.AddDays(-14)), "yyyyMMdd");
                    break;
                default:
                    break;
            }

            string key = string.Concat(CPYXARMORY_CACHED_KEY, ".", weekEndDate);

            List<Armory> list = CacheManager.DefaultCache.Get<List<Armory>>(key);

            if (list == null)
            {
                try
                {
                    lock (objCpyxArmory)
                    {
                        list = CacheManager.DefaultCache.Get<List<Armory>>(key);

                        if (list == null)
                        {
                            string msg = string.Empty;
                            ArmoryDal armoryDal = new ArmoryDal();

                            list = armoryDal.GetArmory(ConfigHelper.CpyxYxbCount, 0, weekEndDate, out msg);

                            if (list == null || list.Count == 0)
                            {
                                list = new List<Armory>();
                            }

                            if (list != null && list.Count > 0)
                            {
                                MC_MyInfo myInfo = null;
                                MyInfoBll myInfoBll = new MyInfoBll();

                                foreach (Armory armory in list)
                                {
                                    armory.time = StringHelper.FormatDateTime(dtNow, "M-d H:mm");
                                    myInfo = myInfoBll.GetMyInfo(armory.UserId);

                                    if (myInfo != null)
                                    {
                                        if (!string.IsNullOrEmpty(myInfo.UserName))
                                        {
                                            armory.UserName = StringHelper.FormatUserName(myInfo.UserName);
                                        }
                                        else
                                        {
                                            if (!string.IsNullOrEmpty(myInfo.Mobile))
                                            {
                                                armory.UserName = myInfo.Mobile;
                                            }
                                            else
                                            {
                                                if (!string.IsNullOrEmpty(myInfo.Email))
                                                {
                                                    armory.UserName = myInfo.Email;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (list != null)
                            {
                                switch (flag)
                                {
                                    case "pw": //上周
                                    case "ppw": //上上周
                                        if (dtNow.DayOfWeek == DayOfWeek.Monday && dtNow.TimeOfDay <= new TimeSpan(1, 0, 0))
                                        {
                                            CacheManager.DefaultCache.Set<List<Armory>>(key, list, 10);
                                        }
                                        else
                                        {
                                            CacheManager.DefaultCache.Set<List<Armory>>(key, list, 60 * 24);
                                        }
                                        break;
                                    default:
                                        CacheManager.DefaultCache.Set<List<Armory>>(key, list, ConfigHelper.Cpyx);
                                        break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取排行榜数据失败");
                }
            }

            if (list != null && list.Count > 0)
            {
                List<Armory> retList = list.Take(50).ToList();

                if (retList.Find(lst => lst.UserId == userid) == null)  //不在前50名
                {
                    Armory my = list.Find(lst => lst.UserId == userid); //从TOP500中查找

                    if (my != null)
                    {
                        retList.Add(my);
                    }
                }

                result = JsonHelper.ToJson(retList);
            }

            return result;
        }

        /// <summary>
        /// 我的记录
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="pageNum"></param>
        /// <param name="beginNum"></param>
        /// <returns></returns>
        public string GetUserResult(int userID,int type)
        {
            string ret = string.Empty;

            try
            {
                string msg = string.Empty;

                UserResultDal userResultDal = new UserResultDal();

                List<UserResult> list = userResultDal.GetUserResult(userID, 100, 0, type, out msg);

                if (list != null && list.Count > 0)
                {
                    ret = JsonHelper.ToJson(list);
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "获取我的记录失败");
            }            

            return ret;
        }

        public string GetResetTime(DateTime dt)
        {
            if (dt.DayOfWeek != DayOfWeek.Sunday)
            {
                return Recursion(dt,1);
            }
            else
            {
                if (dt.Hour == 23)
                {
                    return string.Concat("约", 59 - dt.Minute, "分钟");
                }
                else
                {
                    return string.Concat("约", 23 - dt.Hour, "小时");
                }
            }
        }

        private string Recursion(DateTime dt,int days)
        {
            if (dt.DayOfWeek == DayOfWeek.Sunday)
            {
                return string.Concat(days, "天");
            }
            else
            {
                days++;

                return Recursion(dt.AddDays(1), days);
            }
        }

        /// <summary>
        /// 发奖
        /// </summary>
        public static void ProcessAward()
        {
            try
            {
                DateTime dtNow = DateTime.Now;

                if (dtNow.DayOfWeek == DayOfWeek.Monday && dtNow.TimeOfDay >= new TimeSpan(8, 50, 0) && dtNow.TimeOfDay < new TimeSpan(9, 10, 0))
                {
                    string msg = string.Empty;

                    string weekEndDate = StringHelper.FormatDateTime(DateTimeHelper.GetSundayDate(dtNow.AddDays(-7)), "yyyyMMdd");

                    ArmoryDal armoryDal = new ArmoryDal();

                    List<Armory> list = armoryDal.GetArmory(50, 0, weekEndDate, out msg);

                    if (list != null && list.Count > 0)
                    {
                        MyInfoBll myInfoBll = new MyInfoBll();

                        foreach (Armory armory in list)
                        {
                            if (armory.Idx <= 3 || armory.Idx > 50)
                            {
                                continue;
                            }

                            if (!myInfoBll.AddMyFlow(armory.UserId, 20, string.Concat(weekEndDate, "周K线英雄第", armory.Idx, "名")))
                            {
                                LogManager.DefaultLogger.Error(null, string.Concat("K线英雄发奖失败，userid：", armory.UserId, "，Idx：", armory.Idx));
                            }
                            else
                            {
                                LogManager.DefaultLogger.Debug(string.Concat(armory.UserId, " ", weekEndDate, "周K线英雄第", armory.Idx, "名，20i豆发放成功"));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "K线英雄发奖失败");
            }
        }
    }
}
